package xyz.erupt.jpa.model;

import xyz.erupt.annotation.fun.DataProxy;
import xyz.erupt.annotation.query.Condition;
import xyz.erupt.core.context.MetaContext;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 逻辑删除
 *
 * @author Ajian
 * @date 2022-08-05 00:52
 */
public class SoftDelModelProxy implements DataProxy<SoftDelModel> {

    @Override
    public String beforeFetch(List<Condition> conditions,Class<?> eruptClazz) {
        //所有的sql都加上删除条件的筛选
        //return " (del_flag=0 or del_flag is null) ";
        String entityName = eruptClazz.getSimpleName();
        StringBuilder hql = new StringBuilder(" ");
        hql.append("(").append(entityName).append(".delFlag=0 ");
        hql.append(" or ").append(entityName).append(".delFlag is null");
        hql.append(") ");
        return hql.toString();
    }

    @Override
    public void beforeUpdate(SoftDelModel entity) {
        if (entity.getDelFlag() != null && entity.getDelFlag().equals(true)) {
            this.beforeDelete(entity);
        }
    }

    @Override
    public void beforeDelete(SoftDelModel entity) {
        entity.setDelFlag(true);
        entity.setDelOperatorAccount(MetaContext.getUser().getAccount());
        entity.setDelTime(LocalDateTime.now());
    }
}
